#!/bin/bash
#初始化beetle机器,创建ssh密钥,使用root用户运行
error_exit(){
	echo "ERROR:初始化beetle机器失败, $1"
	exit 1
}

#beetle用户所在组
group="beetle"
#新建用户名
user="beetle"
#svn用户名
svnUserName=$1
#svn密码
svnPass=$2
#svn校验路径
svnPath=$3

localPath=`pwd`

echo "==========初始化beetle机器开始=========="
#判断用户是否存在
isUser=`id -nu ${user} 2> /dev/null`
isGroup=`egrep "^${group}" /etc/group`
if [ ! ${isGroup} ]
then
    echo "==========创建用户组${group}开始=========="
    groupadd ${group} || error_exit "创建用户组${group}失败"
    echo "==========创建用户组${group}结束=========="
fi

if [ ! ${isUser} ]
then
    echo "==========创建用户${user}开始=========="
    useradd -s /bin/bash -g ${group} -d /home/${user} -m ${user} || error_exit "创建用户${user}失败"
    echo "==========创建用户${user}结束=========="
fi

cd /usr/local
if [ ! -e Beetle ]
then
	mkdir Beetle || error_exit "创建文件夹Beetle失败"
	chown -R ${user}:${group} Beetle/
	chmod 770 Beetle/
	setfacl -m d:g:${group}:rwx /usr/local/Beetle
fi
cd Beetle/
if [ ! -e ssh ]
then
	mkdir ssh || error_exit "创建文件夹ssh失败"
	chown -R ${user}:${group} ssh/
	chmod 770 ssh/
#	setfacl -m d:g:${group}:r-- /usr/local/Beetle/ssh
fi

cd ssh
if [ ! -e id_rsa ]
then
	cd ${localPath}
    #生成免密密钥
    echo "==========生成密钥文件开始=========="
    expect beetle_create_key.sh ${user} || error_exit "生成密钥文件失败"
    echo "==========生成密钥文件结束=========="
fi
if [ ! ${isUser} ]
then
    echo "==========拷贝ssh密钥${user}开始=========="
    cd /home/${user}
    if [ ! -e .Beetle ]
    then
        mkdir .Beetle || error_exit "创建文件夹~/.Beetle失败"
    fi
    cp /usr/local/Beetle/ssh/common_id_rsa /home/${user}/.Beetle/common_id_rsa || error_exit "拷贝密钥文件到用户目录失败"
    chown -R ${user}:${group} /home/${user}/.Beetle
    echo "==========拷贝ssh密钥${user}结束=========="
fi
echo "==========校验svn登录开始=========="
cd ${localPath}
expect beetle_validate_svn.sh ${svnUserName} ${svnPath} ${svnPass} ${user} || error_exit "校验svn登录失败"
echo "==========校验svn登录结束=========="
echo "==========初始化beetle机器成功=========="